﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using log4net;
using Mangox.Model.MangoxDB;
using Mangox.Common;
using System.Diagnostics;
using Mangox.Model.Stock;
using Mangox.Common.Tookit;
using Mangox.Model.Common;

namespace Mangox.BLL.Mangox
{
    /// <summary>
    /// 用户操作
    /// 增删改查案例，示例
    /// </summary>
    public class MgxUserBLL
    {
        protected static ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        private static string className = (new StackTrace()).GetFrame(1).GetMethod().ReflectedType.Name + "/";
        Random rd = new Random();

        public List<M_User> GetUserList()
        {
            List<M_User> list = null;
            using (MangoxDBEntities dbContext = new MangoxDBEntities())
            {
                list = dbContext.M_User.ToList();

                //var list2 = dbContext.Users.Where(u => u.Id < 3);//延迟查询
                //var list4 = list2.Where(u => u.Name.Length < 3).OrderBy(u => u.Id);

                //var list3 = dbContext.Users.Where(u => u.Id < 3).ToList();
            }

            return list;
        }

        /// <summary>
        /// 登陆
        /// </summary>
        /// <param name="loginName"></param>
        /// <param name="passWord"></param>
        /// <returns></returns>
        public M_User GetUser(string loginName, string passWord)
        {
            M_User user = null;
            using (MangoxDBEntities dbContext = new MangoxDBEntities())
            {
                try
                {
                    //var tempList1 = dbContext.M_User.Where(u => u.UserID == userID).ToList();

                    //登陆后写入登陆LoginCount...

                    int userid = 0;
                    int.TryParse(loginName, out userid);

                    var tempList = dbContext.M_User.Where(u => 
                        (u.LoginName == loginName || u.UserID == userid || u.Openid == loginName) 
                        && u.Password == passWord
                        && u.State == 1).ToList() as List<M_User>;

                    if (tempList != null && tempList.Count > 0)
                    {
                        user = tempList[0];
                        //log.Info(className + $"登陆成功 GetUser loginName-{loginName}");
                    }
                }
                catch (Exception ex)
                {
                    log.Error(className + $"登陆失败 GetUser fail-{ex.ToString()}");
                }
            }
            return user;
        }
        
        /// <summary>
        /// 通用逻辑
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public M_User GetUser(MgxToken token)
        {
            M_User user = null;
            using (MangoxDBEntities dbContext = new MangoxDBEntities())
            {
                try
                {
                    var tempList = dbContext.M_User.Where(u => u.UserID == token.UserID).ToList() as List<M_User>;
                    if (tempList != null && tempList.Count == 1)
                    {
                        user = tempList[0];
                        log.Info(className + $"登陆成功 GetUser {token.UserID}");
                    }
                    else if (tempList.Count > 1)
                    {
                        log.Info(className + $"GetUser {token.UserID} 查询到多条数据-{JsonCommon.ToJson(tempList)}");
                        return null;
                    }
                }
                catch (Exception ex)
                {
                    log.Error(className + $"登陆失败 GetUser fail-{ex.ToString()}");
                }
            }
            return user;
        }

        /// <summary>
        /// 根据微信openid获取用户
        /// 可能弃用
        /// </summary>
        /// <param name="openid"></param>
        /// <returns></returns>
        public M_User GetUserApplet(string openid)
        {
            M_User user = null;

            try
            {
                using (MangoxDBEntities dbContext = new MangoxDBEntities())
                {
                //这种写法openid必须是主键，否则会报错
                //user = dbContext.User.Find(openid);

                    //var tempList1 = dbContext.M_User.Where(u => u.Openid == openid).ToList();

                    var tempList = dbContext.M_User.Where(u => u.Openid == openid).ToList() as List<M_User>;
                    if (tempList != null && tempList.Count > 0)
                    {
                        user = tempList[0];
                        log.Info($"小程序使用openid-{openid} 登陆成功");
                    }
                    else
                    {
                        log.Info($"小程序使用openid-{openid} 登陆失败，userList-{JsonCommon.ToJson(tempList)}");
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error(className + $"小程序使用openid-{openid} 登陆失败 fail-{ex}");
                throw ex;
            }
            return user;
        }

        /// <summary>
        /// 根据Hash获取用户
        /// 查询发红包用户名
        /// </summary>
        /// <param name="mgxHashID"></param>
        /// <returns></returns>
        public M_User GetUserByMgxHashID(string mgxHashID)
        {
            M_User user = null;

            try
            {
                if (string.IsNullOrWhiteSpace(mgxHashID))
                {
                    return null;
                }
                using (MangoxDBEntities dbContext = new MangoxDBEntities())
                {
                    var tempList = dbContext.M_User.Where(u => u.MgxHashID == mgxHashID).ToList() as List<M_User>;
                    if (tempList != null && tempList.Count > 0)
                    {
                        user = tempList[0];
                        log.Info($"使用mgxHashID-{mgxHashID} 登陆成功，mgxHashID-{mgxHashID}");
                    }
                    else
                    {
                        log.Info($"使用mgxHashID-{mgxHashID} 登陆失败，userList-{JsonCommon.ToJson(tempList)}");
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error(className + $"使用mgxHashID-{mgxHashID} 登陆失败 fail-{ex}");
                throw ex;
            }
            return user;
        }

        /// <summary>
        /// 根据微信LoginName获取用户
        /// </summary>
        /// <param name="openid"></param>
        /// <returns></returns>
        public List<M_User> GetUserByLoginName(string loginName)
        {
            List<M_User> list = null;
            using (MangoxDBEntities dbContext = new MangoxDBEntities())
            {
                try
                {
                    var tempList = dbContext.M_User.Where(u => u.LoginName == loginName).ToList() as List<M_User>;
                    if (tempList != null && tempList.Count > 0)
                    {
                        list = tempList;
                    }
                }
                catch (Exception ex)
                {
                    log.Error(className + $"获取用户失败 loginName-{loginName} fail-{ex}");
                }
            }
            return list;
        }

        /// <summary>
        /// 根据UserID获取用户
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        public List<M_User> GetUserByUserID(string userid, AppType appType)
        {
            List<M_User> list = null;
            using (MangoxDBEntities dbContext = new MangoxDBEntities())
            {
                try
                {
                    var id = Convert.ToInt32(userid);
                    var tempList = dbContext.M_User.Where( u => u.UserID == id
                        && u.State == (int)UserStatus.Enabled
                        && u.AppType == (int)appType
                        ).ToList() as List<M_User>;
                    if (tempList != null && tempList.Count > 0)
                    {
                        list = tempList;
                    }
                }
                catch (Exception ex)
                {
                    log.Error(className + $"获取用户失败 userid-{userid} fail-{ex}");
                }
            }
            return list;
        }

        /// <summary>
        /// 获取用户表最大的id
        /// </summary>
        /// <returns></returns>
        public int GetUserMax()
        {
            try
            {
                using (MangoxDBEntities dbContext = new MangoxDBEntities())
                {
                    return dbContext.M_User.Max(c => c.ID);
                }
            }
            catch (Exception ex)
            {
                log.Error(className + $"获取最大id失败 fail-{ex}");
            }
            return 0;
        }

        public bool AddUser(M_User user)
        {
            var flag = false;
            try
            {
                log.Info($"添加用户信息-{JsonCommon.ToJson(user)}");

                using (MangoxDBEntities dbContext = new MangoxDBEntities())
                {
                    var temp = new M_User();
                    ObjectReflection.AutoMapping(user, temp);

                    dbContext.M_User.Add(temp);
                    flag = dbContext.SaveChanges() > 0;
                }
            }
            catch (Exception ex)
            {
                log.Error(className + $"添加用户失败 user-{JsonCommon.ToJson(user)} fail-{ex}");
                throw ex;
            }
            return flag;
        }

        /// <summary>
        /// 必须先查询出来再赋值更新，必须是当前dbContext，不能些两个方法的dbContext
        /// </summary>
        /// <param name="user"></param>
        /// <param name="type">1小程序(有小程序授权信息)，2其他终端</param>
        /// <returns></returns>
        public bool UpdateUser(M_User user, int type)
        {
            var flag = false;
            M_User us = null;
            try
            {
                log.Info(className + $"更新用户信息 type-{type} user{JsonCommon.ToJson(user)}");
                using (MangoxDBEntities dbContext = new MangoxDBEntities())
                {
                    var list = dbContext.M_User.Where(u => u.UserID == user.UserID).ToList() as List<M_User>;
                    if (list.Count <= 0)
                    {
                        return false;
                    }

                    us = list[0];

                    //给需要修改的字段赋值
                    //user.MgxHashID = p.MgxHashID;
                    us.LoginCount = ++us.LoginCount;
                    us.LastLoginTime = DateTime.Now;

                    //都需要验证
                    us.UserName = string.IsNullOrEmpty(user.UserName) ? us.UserName : user.UserName;
                    us.ERCAddress = string.IsNullOrEmpty(user.ERCAddress) ? us.ERCAddress : user.ERCAddress;
                    us.Mobile = string.IsNullOrEmpty(user.Mobile) ? us.Mobile : user.Mobile;
                    us.Email = string.IsNullOrEmpty(user.Email) ? us.Email : user.Email;
                    us.Gender = string.IsNullOrEmpty(user.Gender) ? us.Gender : user.Gender;

                    //us.Password = user.Password; //密码需要重复验证，复杂度等

                    if (type == 1)
                    {
                        us.NickName = user.NickName;
                        us.Session_key = user.Session_key;
                        us.UnionId = user.UnionId;
                        us.AvatarUrl = user.AvatarUrl;
                        us.Province = user.Province;
                        us.City = user.City;
                        us.Language = user.Language;
                        us.Country = user.Country;
                        us.Source = user.Source;
                    }

                    flag = dbContext.SaveChanges() > 0;
                }
            }
            catch (Exception ex)
            {
                log.Error(className + $"更新用户信息 user{JsonCommon.ToJson(user)} fail-{ex.ToString()}");
            }
            return flag;
        }

        /// <summary>
        /// 用户授权后保存城市、头像等信息
        /// 跟新输入ERC地址空投
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public M_User UpdateAuthUser(WxAuthParam param)
        {
            M_User us = null;
            try
            {
                using (MangoxDBEntities dbContext = new MangoxDBEntities())
                {

                    us = (dbContext.M_User.Where(u => u.Openid == param.openid).ToList() as List<M_User>)[0];

                    us.IsAuth = 1;
                    us.NickName = param.nickName;
                    us.Gender = param.gender;
                    us.Language = param.language;
                    us.City = param.city;
                    us.Province = param.city;
                    us.Country = param.country;
                    us.AvatarUrl = param.avatarUrl;
                    us.ERCAddress = param.ERCAddress;
                    us.Mobile = param.Mobile;
                    us.Email = param.Email;
                    

                    if (dbContext.SaveChanges() > 0)
                    {
                        log.Info(className + $"UpdateAuthUser {param.openid}授权成功，NickName-{us.NickName}");
                        return us;
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error(className + $"UpdateAuthUser fail-{ex}");
            }
            return us;
        }

        public bool DelUser(M_User user)
        {
            using (MangoxDBEntities dbContext = new MangoxDBEntities())
            {
                dbContext.M_User.Remove(user);
                return dbContext.SaveChanges() > 0;
            }
        }


        /// <summary>
        /// 生成用户账号
        /// 目前支持到7位 百万
        /// </summary>
        /// <returns></returns>
        public int CreateUserID()
        {
            int uid = 0;
            int max = 0;
            string rdStr = "";
            try
            {
                MgxUserBLL bll = new MgxUserBLL();
                max = bll.GetUserMax() + 1;
                //随机混淆id
                rdStr = rd.Next(1000000, 9999999).ToString();
                rdStr = rdStr.Substring(0, rdStr.Length - max.ToString().Length);
                uid = Convert.ToInt32(rdStr + max.ToString());

                log.Info(className + $"创建UserID成功 uid-【{uid}】 rd-{rdStr} max-{max}");
            }
            catch (Exception ex)
            {
                log.Error(className + $"创建UserID异常 uid-【{uid}】 rd-{rdStr} max-{max} Fail-{ex.ToString()}");
            }
            return uid;
        }

        #region 水龙头活动

        /// <summary>
        /// 登陆 水龙头活动，用ERC地址/用户名匿名登陆
        /// </summary>
        /// <param name="ercAddress">ercAddress</param>
        /// loginName可能等于userid
        /// <returns></returns>
        public M_User GetUserSlt(string loginName, string ercAddress, int appType)
        {
            M_User user = null;
            using (MangoxDBEntities dbContext = new MangoxDBEntities())
            {
                try
                {
                    //var tempList1 = dbContext.M_User.Where(u => u.UserID == userID).ToList();
                    //登陆后写入登陆LoginCount...

                    int userid = 0;
                    int.TryParse(loginName, out userid);

                    var tempList = dbContext.M_User.Where(u =>
                        (u.LoginName == loginName || u.UserID == userid || u.Openid == loginName)
                        || u.ERCAddress == ercAddress
                        && u.AppType == appType
                        && u.State == 1).ToList() as List<M_User>;

                    if (tempList != null && tempList.Count > 0)
                    {
                        user = tempList[0];
                        log.Info(className + $"水龙头登陆成功 loginName-{loginName}");
                    }
                }
                catch (Exception ex)
                {
                    log.Error(className + $"水龙头登陆失败 GetUser fail-{ex.ToString()}");
                }
            }
            return user;
        }

        /*
        /// <summary>
        /// 根据ercAddress获取用户
        /// </summary>
        /// <param name="ercAddress"></param>
        /// <returns></returns>
        public M_User GetUserByERCAddress(string ercAddress, AppType appType)
        {
            M_User user = null;

            try
            {
                if (string.IsNullOrWhiteSpace(ercAddress))
                {
                    return null;
                }
                using (MangoxDBEntities dbContext = new MangoxDBEntities())
                {
                    var tempList = dbContext.M_User.Where(u => u.ERCAddress == ercAddress 
                        && u.State == (int)UserStatus.Enabled
                        && u.AppType == (int)appType
                    ).ToList() as List<M_User>;
                    if (tempList != null && tempList.Count > 0)
                    {
                        user = tempList[0];
                        log.Info($"水龙头活动-{ercAddress} 登陆成功，mgxHashID-{ercAddress}");
                    }
                    else
                    {
                        log.Info($"水龙头活动-{ercAddress} 登陆失败，userList-{JsonCommon.ToJson(tempList)}");
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error(className + $"水龙头活动-{ercAddress} 登陆失败 fail-{ex}");
                throw ex;
            }
            return user;
        }*/

        #endregion



    }

}
